import axios from 'axios';
import { BusinessError } from './errors.js';
import config from '../config/index.js';

/**
 * 子系统K API客户端
 * 根据PRD要求，子系统K的API返回格式为 {code: 0, message: 'ok', data: {}}
 * 调用时需要加上x-api-key请求头
 */
class SystemKClient {
  constructor(baseUrl, apiKey) {
    this.baseUrl = baseUrl ? baseUrl.replace(/\/$/, '') : '';
    this.apiKey = apiKey;
    this.timeout = config.serviceIntegration?.timeout || 30000;
  }

  /**
   * 发送HTTP请求到子系统K
   * @param {string} path - API路径
   * @param {string} method - HTTP方法 (GET, POST, PUT, DELETE)
   * @param {object} params - 请求参数
   * @param {object} options - 额外选项
   * @returns {Promise<object>} 返回API响应的data部分
   */
  async request(path, method = 'GET', params = {}, options = {}) {
    if (!this.baseUrl) {
      throw new BusinessError('子系统K基础URL未配置');
    }

    if (!this.apiKey) {
      throw new BusinessError('子系统K API密钥未配置');
    }

    // 构建完整URL
    const url = `${this.baseUrl}${path.startsWith('/') ? path : `/${path}`}`;

    // 构建请求配置
    const requestConfig = {
      method: method.toUpperCase(),
      url,
      timeout: this.timeout,
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': this.apiKey,
        ...options.headers
      }
    };

    // 添加请求参数
    if (method.toUpperCase() === 'GET') {
      requestConfig.params = params;
    } else {
      requestConfig.data = params;
    }

    try {
      console.log(`📡 调用子系统K API: ${method.toUpperCase()} ${url}`, params);
      
      const response = await axios(requestConfig);
      const responseData = response.data;

      console.log(`✅ 子系统K API响应:`, responseData);

      // 验证响应格式
      this.validateResponse(responseData);

      return responseData;
    } catch (error) {
      console.error(`❌ 子系统K API调用失败: ${method.toUpperCase()} ${url}`, error.message);
      
      if (error.response) {
        // HTTP错误响应
        const errorData = error.response.data;
        if (errorData && typeof errorData === 'object') {
          throw new BusinessError(`子系统K API错误: ${errorData.message || errorData.error || '未知错误'}`);
        } else {
          throw new BusinessError(`子系统K API HTTP错误: ${error.response.status} ${error.response.statusText}`);
        }
      } else if (error.code === 'ECONNREFUSED') {
        throw new BusinessError('无法连接到子系统K，请检查网络连接和URL配置');
      } else if (error.code === 'ETIMEDOUT') {
        throw new BusinessError('子系统K API调用超时，请稍后重试');
      } else {
        throw new BusinessError(`子系统K API调用失败: ${error.message}`);
      }
    }
  }

  /**
   * 验证子系统K的响应格式
   * @param {object} responseData - 响应数据
   */
  validateResponse(responseData) {
    if (!responseData || typeof responseData !== 'object') {
      throw new BusinessError('子系统K响应数据格式错误：不是有效的JSON对象');
    }

    if (responseData.code !== 0) {
      throw new BusinessError(`子系统K业务错误: ${responseData.message || '未知错误'} (code: ${responseData.code})`);
    }

    if (!responseData.hasOwnProperty('data')) {
      throw new BusinessError('子系统K响应格式错误：缺少data字段');
    }
  }

  /**
   * 获取专家列表
   * @param {string} path - API路径（从配置中获取）
   * @param {object} params - 查询参数
   * @returns {Promise<Array>} 专家列表
   */
  async getExpertList(path, params = {}) {
    const response = await this.request(path, 'GET', params);

    if (!Array.isArray(response.data)) {
      throw new BusinessError('子系统K返回的专家列表格式错误：data字段应为数组');
    }

    return response.data;
  }

  /**
   * 获取专家详情
   * @param {string} path - API路径（从配置中获取）
   * @param {number|string} expertId - 专家ID
   * @returns {Promise<object>} 专家详情
   */
  async getExpertDetail(path, expertId) {
    const detailPath = `${path}/${expertId}`;
    const response = await this.request(detailPath, 'GET');

    if (!response.data || typeof response.data !== 'object') {
      throw new BusinessError('子系统K返回的专家详情格式错误：data字段应为对象');
    }

    return response.data;
  }

  /**
   * 获取问答详情
   * @param {string} path - API路径（从配置中获取，包含{request_id}占位符）
   * @param {string} requestId - 问答的request_id
   * @returns {Promise<object>} 问答详情
   */
  async getQaDetail(path, requestId) {
    // 替换路径中的占位符
    const detailPath = path.replace('{request_id}', requestId);
    const response = await this.request(detailPath, 'GET');

    if (!response.data || typeof response.data !== 'object') {
      throw new BusinessError('子系统K返回的问答详情格式错误：data字段应为对象');
    }

    return response.data;
  }

  /**
   * 测试连接
   * @param {string} path - 测试路径（可选，默认使用健康检查路径）
   * @returns {Promise<object>} 测试结果
   */
  async testConnection(path = '/health') {
    try {
      const response = await this.request(path, 'GET');
      return {
        success: true,
        message: '连接测试成功',
        data: response.data
      };
    } catch (error) {
      return {
        success: false,
        message: error.message,
        data: null
      };
    }
  }
}

export default SystemKClient;
